package sanger;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.commons.io.filefilter.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * A simple utility class to wrap checks and other functionality for the
 * session class.
 * @author doskias
 */
public class Utilities {

    /**
     * Checks whether the client is logged in based on session information
     * @param session - the session object
     * @return true or false - depending on whether the user is logged or not.
     */
    public static boolean isLogged(HttpSession session) {
        if (session.getAttribute("auth") != null
                && session.getAttribute("auth").toString().equals("logged")) {
            return true;
        }
        return false;
    }

    /**
     *  Simple utility function used to redirect users who are not logged in.
     * @param session
     * @param request
     * @param response 
     */
    public static void logOrRedir(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        if (!Utilities.isLogged(session)) {
            try {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } catch (IOException ex) {
                Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    }

    /**
     * Tries to authenticate a username/string tuple against the db of users
     * @param name - desired username
     * @param pass - desired password
     * @return - True on success or False otherwise
     * @throws FileNotFoundException
     * @throws IOException 
     */
    public static boolean authenticate(String name, String pass) throws FileNotFoundException, IOException {

        String line;
        String[] tokens;
        BufferedReader bf = new BufferedReader(new FileReader(Constants.USER_FILE));

        while ((line = bf.readLine()) != null) {

            tokens = line.split(":");
            if (tokens[0].equals(name) && tokens[1].equals(pass)) {

                System.out.println("Successfully logged in");
                return true;
            }
        }

        return false;
    }

    /**
     * List file of the current user in the tmp upload directory
     * Used just for testing.
     * @param request
     * @param response
     * @throws IOException 
     */
//    public static void listFiles(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        String context = request.getContextPath();
//        String filter = request.getSession().getAttribute("uname") + "_";
//        PrintWriter out = response.getWriter();
//        File dir = new File(Constants.UPLOAD_DIR);
//        String[] files = dir.list(new PrefixFileFilter(filter));
//        
//        for (int i = 0; i < files.length; i++) {
//                    
//        response.setContentType("text/plain");
//        out.println("<a href=" + context + "/" + files[i] + ">" + files[i] + "</a>");
//        out.println("<a href=" + context + "/Delete?n=" + files[i] + "> Delete</a>");
//        out.println("<br/>");
//            
//          
//        }
//    }
    /**
     * List files of the current user on AWS.
     * @param request
     * @param response
     * @throws IOException 
     */
    public static void listAWSFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

        AmazonS3 s3 = Constants.getS3Obj();
        String context = request.getContextPath();
        String prefix = request.getSession().getAttribute("uname") + "_";
        PrintWriter out = response.getWriter();
        int prefixLen = (Constants.AWS_DIR + prefix).length();


        ObjectListing objectListing = s3.listObjects(new ListObjectsRequest()
                .withBucketName(Constants.BUCKET)
                .withPrefix(Constants.AWS_DIR + prefix));
        for (S3ObjectSummary objectSummary : objectListing.getObjectSummaries()) {

            String origName = objectSummary.getKey().substring(prefixLen);

            out.println(" - <a href=" + context + "/Download?n=" + origName + ">" + origName + "</a>"
                    + "(size = " + objectSummary.getSize() + ")"
                    + "   <a href=" + context + "/Delete?n=" + origName + ">Delete</a>");
            out.println("<br/>");
        }

        System.out.println();
    }
}
